package com.strongbj.iot.devices.newlight.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.strongbj.iot.devices.newlight.entity.BindNum;
import com.strongbj.iot.devices.newlight.entity.Tag;
import com.strongbj.iot.devices.newlight.entity.TagAccess;
import com.strongbj.iot.devices.newlight.entity.TagReg;
import com.strongbj.iot.devices.newlight.mapper.TagRegMapper;
import com.strongbj.iot.devices.newlight.service.TagRegService;

@Service("tagRegService")
public class TagRegServiceImpl extends ServiceImpl<TagRegMapper, TagReg> implements TagRegService {

	@Autowired
	private TagRegMapper tagRegMapper;

	@Override
	public void clearTagReg() {
		tagRegMapper.deleteAllTagReg();
	}

	@Override
	public List<Tag> bingTagReg(Map<String, TagReg> bestList, Map<String, TagReg> secList) {
		// 查询读写器绑定标签数量
		List<BindNum> nums = tagRegMapper.selectBindNumByReader();
		Map<String, Integer> map = new HashMap<String, Integer>();
		for (BindNum bn : nums) {
			map.put(bn.getCode(), bn.getNum());
		}
		List<Tag> tags = new ArrayList<Tag>();
		
		if(bestList != null) {
			// 循环信号质量数据
			for (String key : bestList.keySet()) {
				// 判断reader绑定标签数量是否达到上限
				if (map.get(bestList.get(key).getReader()) >= 800) {
					// 如果达到reader标签数量上限，查询第二质量好reader绑定
					if(secList!=null) {
						if (secList.get(key) != null) {
							Tag t = new Tag();
							t.setIp(secList.get(key).getTagIp());
							t.setReader(secList.get(key).getReader());
							tags.add(t);
						}	
					}		
				} else {
					Tag t = new Tag();
					t.setIp(bestList.get(key).getTagIp());
					t.setReader(bestList.get(key).getReader());
					tags.add(t);
				}
			}
		}
		return tags;
	}

	@Override
	public Tag bingTagReg(TagAccess tagAccess) {
		List<BindNum> nums = tagRegMapper.selectBindNumByReader();
		Map<String, Integer> numMap = new HashMap<String, Integer>();
		for (BindNum bn : nums) {
			numMap.put(bn.getCode(), bn.getNum());
		}
		
		TagReg tagReg = null;
		for(TagReg tr : tagAccess.getTagRegMap().values()) {
			if(tagReg==null || 
					(tr.getQuality()> tagReg.getQuality() && numMap.containsKey(tr.getReader()) && numMap.get(tr.getReader())<1000)){
				tagReg = tr;
			}
		}
		Tag tag = new Tag();
		tag.setIp(tagReg.getTagIp());
		tag.setReader(tagReg.getReader());
		return tag;
	}
}
